package com.tgy.leetcode;

import java.util.Arrays;

public class _面试题_17_21_直方图的水量 {

    public static int trap(int[] height) {

        int len = height.length;
        int[] leftToRight = new int[len];
        int[] rightToLeft = new int[len];

        int water = 0;

        for (int i = 0; i < len; i++) {

            leftToRight[i] = -1;
            rightToLeft[i] = len;
        }

        for (int i = 1; i < len; i++) {

            int preIndex = i - 1;

            while (preIndex >= 0) {

                if (height[i] < height[preIndex]) {

                    leftToRight[i] = leftToRight[preIndex] >= 0 ? leftToRight[preIndex]:preIndex;
                    break;
                }else {
                    preIndex = leftToRight[preIndex];
                }
            }
        }

        for (int i = len - 2; i >= 0; i--) {

            int nextIndex = i+1;
            while (nextIndex < len) {

                if (height[i] < height[nextIndex]) {

                    rightToLeft[i] = rightToLeft[nextIndex] < len ? rightToLeft[nextIndex]:nextIndex;
                    break;
                }else {

                    nextIndex = rightToLeft[nextIndex];
                }
            }
        }

        for (int i = 0; i < len; i++) {

            if (leftToRight[i] >= 0 && rightToLeft[i] < len) {

                water += (Math.min(height[leftToRight[i]],height[rightToLeft[i]]) - height[i]);
            }
        }
        return water;
    }

    public static void main(String[] args) {

        int[] heights = {0,1,0,2,1,0,1,3,2,1,2,1};

        System.out.println(trap(heights));
    }
}
